/*
 *  Copyright 2008 Danny Lagrouw
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License. 
 */
package org.bastion.service.impl;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Pattern;

import org.bastion.service.ConfigService;

/**
 * A service that can read and (in the future) store properties in files and
 * Properties objects.
 * 
 * @author Danny
 */
public class PropertiesFileConfigService implements ConfigService {

    private Properties properties;

    public PropertiesFileConfigService(Properties properties) {
        this.properties = properties;
    }

    public PropertiesFileConfigService(Reader propertiesReader) throws IOException {
        properties = new Properties();
        properties.load(propertiesReader);
    }

    public PropertiesFileConfigService(String propertiesFileName) throws IOException {
        properties = new Properties();
        properties.load(new FileReader(propertiesFileName));
    }

    public Object getConfig(String propertyName) {
        checkProperties();
        return properties.get(propertyName);
    }

    public Map<String, Object> getConfig(Pattern propertyFilter) {
        checkProperties();
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        for (Object key : properties.keySet()) {
            String keyStr = (String) key;
            if (propertyFilter.matcher(keyStr).matches()) {
                map.put(keyStr, properties.get(key));
            }
        }
        return map;
    }

    private void checkProperties() {
        if (properties == null) {
            throw new IllegalStateException("No properties loaded");
        }
    }

}
